#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    foreach(const QSerialPortInfo &info, QSerialPortInfo::availablePorts())
    {
        m_listcomboName << info.portName();
    }
    ui->Serial_Number_comboBox->addItems(m_listcomboName);
    flag = 0;
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_Dim_Slider_valueChanged(int value)
{
    QByteArray data(1, value);

    ui->Dim_Value_label->setText(QString::number(value));
    m_reader.write(data);
    qDebug() << value;
}

void MainWindow::on_Serial_Number_comboBox_activated(const QString &arg1)
{
    QSerialPort temp;

    flag = 0;
    foreach(const QSerialPortInfo &info, QSerialPortInfo::availablePorts())
    {
       if(info.portName() == arg1)
       {
        flag = 1;
        com_info = info;
       }
       else
       {
           temp.setPort(info);
           temp.close();
       }
    }

    m_reader.setPort(com_info);
    if(m_reader.open(QIODevice::ReadWrite))
    {
        m_reader.setBaudRate(QSerialPort::Baud115200);
        m_reader.setParity(QSerialPort::NoParity);
        m_reader.setDataBits(QSerialPort::Data8);
        m_reader.setStopBits(QSerialPort::OneStop);
        m_reader.setFlowControl(QSerialPort::NoFlowControl);
        m_reader.clearError();
        m_reader.clear();
    }
}

void MainWindow::on_Open_pushButton_clicked()
{
    if(flag == 1)
    {
        QByteArray data(1, 101);
        m_reader.write(data);
    }
}

void MainWindow::on_Close_pushButton_clicked()
{
    if(flag == 1)
    {
        QByteArray data(1, 102);
        m_reader.write(data);
    }
}

// 在closeEvent内实现具体逻辑
void MainWindow::closeEvent(QCloseEvent *event)
{
   m_reader.close();
}

